const go = new Go();

WebAssembly.instantiateStreaming(fetch("./nes.wasm"), go.importObject)
    .then(async (result) => {
        go.run(result.instance);
    })
    .catch((err) => {
        console.error(err);
    });

// 导入参数对象
const imports = {
    env: {
        log: function (str) {
            console.log(str);
        },
    },
};

let runCount = 0


function drawCanvas(data) {
    const drawData = JSON.parse(data);
    const canvas = document.getElementById("canvas");
    const canvasCtx = canvas.getContext("2d");

    canvasCtx.clearRect(0, 0, 32, 32);

    for (let i = 0; i < 32 * 3 * 32; i += 3) {
        let x = (i / 3) % 32;
        let y = Math.floor(i / 3 / 32);
        let r = drawData[i];
        let g = drawData[i + 1];
        let b = drawData[i + 2];

        canvasCtx.fillStyle = `rgba(${r},${g},${b},255)`;
        canvasCtx.fillRect(x, y, 1, 1);
    }
}

const bufferToArray = async (blob) => {
    const arrayBuffer = await blob.arrayBuffer();
    return new Uint8Array(arrayBuffer);
};

async function getNesDatAndRun() {
    const res = await axios.get("http://localhost:63342/rgones/html/nestest.nes", {
        responseType: 'blob'
    });
    const stream = res.data.stream();
    const reader = stream.getReader();
    const str = Array.from( await bufferToArray(res.data)).toString()

    return `[${str}]`;
}

